import { UserEntity } from "../entities/UserEntity";
import UserModel from "../models/UserModel";

export default class UserDao {
  static async register(user: UserEntity) {
    try {
      const result = await UserModel.create({
        ...user,
      });

      return result.toJSON();
    } catch (err) {
      throw new Error(err.original.message);
    }
  }

  static async login(user: UserEntity): Promise<object | null> {
    try {
      const result = await UserModel.findOne({
        attributes: {
          exclude: ["password", "createdAt", "updatedAt"],
        },
        where: {
          email: user.email,
          password: user.password,
        },
      });

      if (result) {
        return result.toJSON();
      } else {
        return null;
      }
    } catch (err) {
      throw new Error(err.original.message);
    }
  }

  static async whoami(user: UserEntity): Promise<object | null> {
    try {
      const result = await UserModel.findOne({
        attributes: {
          exclude: ["password", "createdAt", "updatedAt"],
        },
        where: {
          ...user,
        },
      });

      if (result) {
        return result.toJSON();
      } else {
        return null;
      }
    } catch (err) {
      throw new Error(err.original.message);
    }
  }

  static async modifyPassword(user: UserEntity): Promise<boolean> {
    try {
      const result = await UserModel.update(
        {
          password: user.password,
        },
        {
          where: {
            email: user.email,
          },
        }
      );

      return result[0] > 0 ? true : false;
    } catch (err) {
      throw new Error(err.original.message);
    }
  }
}
